import Utils from '@/utils/index'
import { View, Text, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { Dialog, ImageViewer, Tag } from 'antd-mobile'
import { useState, useEffect, useMemo } from 'react'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import FileItem from '../myComponent/fileItem'
import Header from '../myComponent/header'
import { useDocumentTitle, useGetFileName, useGetImgInRichText, useGetIsMapArray, useGetOutsideUrl, useResetDate, useTitleCut } from '@/utils/myUtils'
import PopoverDownload from '../myComponent/popoverDownload'
import { useSelector, useDispatch } from 'react-redux'
import LgButton from '../components/button'
import { setIdentityCode, setSysInfo, setToken, setType, setUserInfo } from '@/store/slice'
import { Current } from '@tarojs/runtime'
import { HttpDelete, HttpGet, HttpPut } from '@/network/servers'
import { getBaseUrl, requestSystemUrl } from '@/network/baseUrl'
import Loading from '@/myComponent/load'

import './index.scss'
const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()
var wx = require('weixin-js-sdk')

const requireContext = require.context("../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
    let str = item.replace('./', "").replace('.svg', "")
    fileObj[str] = svgs[index]
})

function App(props) {
    const dispatch = useDispatch()
    const commonData = useSelector((state: any) => state.commonData)

    const {
        userInfo,
        type,
        token
    } = commonData

    const {
        preView,
        previewData
    } = props

    useDocumentTitle('部门公告详情', false)

    const [detail, setDetail] = useState<any>({})
    const [seat, setSeat] = useState<any>()
    const [imgList, setImgList] = useState([
    ])
    const [fileList, setFileList] = useState([
    ])
    const [richTextImg, setRichTextImg] = useState<any>([])
    const [visible, setVisible] = useState(false)
    const [currentFile, setCurrentFile] = useState<any>({})
    const [currentIndex, setCurrentIndex] = useState<any>()

    const handleRecall = () => {
        HttpPut({
            url: "/api/bulletin/manage/callback",
            data: {
                bulletinId: detail.bulletinId
            },
            header: {
                'Authorization': token
            }
        }).then(() => {
            Taro.navigateBack({ delta: 1 })
            setTimeout(() => {
                Taro.showToast({
                    title: '撤回成功'
                })
            }, 500);
        })
    }

    const recall = () => {
        Dialog.show({
            content: <>
                <View className='custom_confirm_box'>
                    <View className='title'>撤回公告</View>
                    <View className='text'>撤回后其他用户将无法查看，
                        确定要撤回该公告吗？</View>
                </View>
            </>,
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'delete',
                        text: '撤回',
                        danger: true,
                        onClick: () => handleRecall()
                    },
                ],
            ],
        })
    }

    const del = () => {
        Dialog.show({
            content: <>
                <View className='custom_confirm_box'>
                    <View className='title'>删除公告</View>
                    <View className='text'>删除后将无法查看
                        确定要删除该公告吗？</View>
                </View>
            </>,
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'delete',
                        text: '删除',
                        danger: true,
                        onClick: () => {
                            HttpDelete({
                                url: '/api/bulletin/manage/del',
                                data: {
                                    bulletinId: detail?.bulletinId
                                }
                            }).then(() => {
                                Taro.navigateBack({ delta: 1 })
                                setTimeout(() => {
                                    Taro.showToast({
                                        title: '删除成功'
                                    })
                                }, 500);
                            })
                        }
                    },
                ],
            ],
        })
    }

    const top = () => {
        HttpPut({
            url: '/api/bulletin/manage/seat',
            data: {
                bulletinId: detail.bulletinId,
                seat: seat == 0 ? 1 : 0
            }
        }).then(() => {
            Taro.showToast({
                title: seat == 0 ? '置顶成功' : '取消置顶成功'
            })
            setSeat(seat == 0 ? 1 : 0)
        })
    }

    const showFile = (item, e?) => {
        e && e.stopPropagation()
        browserController.openFileReader(storage.get(`bulletin_${item.attachmentId}`))
    }

    const download = async (item, index, type) => {
        setVisible(false)
        console.log(item, '*******', index, type)
        let fileName = useGetFileName(item.name)
        let url = item.url
        if (item?.preView || storage.get(`bulletin_${item.attachmentId}`)) { //当前文件已下载，直接预览
            showFile(item)
            return
        }

        if (Utils.getSystemInfo() === 'weapp') {
            const params = await getWxSDKParams([])
            wx.config(params);
            try {
                browserController.openFileForWebview(wx, { fileUrl: url, fileName: fileName })
            } catch (error) {
                Taro.showToast({ title: error, icon: 'none' })
            }
        } else {
            let arr: any = fileList.concat([])
            net.downloadFile({
                url,
                fileName: item.name,
                onProgress: process => {
                    Taro.showToast({
                        icon: 'loading',
                        title: `正在下载${process}%`
                    })
                },
                onSuccess: path => {
                    if (type === 'download') {
                        Taro.showToast({
                            title: '下载成功',
                            icon: 'success',
                            duration: 2000
                        })
                    }
                    arr[index].preView = true
                    storage.set(`bulletin_${item.attachmentId}`, path)
                    setFileList(arr)
                    if (type === 'preview') {
                        browserController.openFileReader(path)  //下载完就预览
                    }
                },
                onError: error => {
                    Taro.showToast({
                        title: '下载失败',
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
        }
    }

    const showPreView = (item) => {
        let arr: any = []
        imgList.map((t: any) => {
            arr.push(t.url)
        })
        ImageViewer.Multi.show({ images: arr, maxZoom: 10 })
    }

    const handleDownload = (item, index, e) => {
        e && e.stopPropagation()
        setCurrentFile(item)
        setCurrentIndex(index)
        setVisible(true)
    }

    const showImg = (e) => {
        let img = e.target?.src, previewUrl = ''
        if (!img) {
            return
        }

        Taro.previewImage({
            current: img,
            urls: richTextImg,
        })

    }

    const getData = () => {
        let bulletinId = Current.router?.params.bulletinId
        let status = Current.router?.params.status
        let pageType = Utils.getQueryVariable('type') || type
        let url = '/api/bulletin/info/board/detail', body = { bulletinId }
        if (pageType === 'admin') {
            if (status == 0) {
                url = '/api/bulletin/info/edit/detail'
            } else if (status == 1) {
                url = '/api/bulletin/info/release/detail'
            }
        }
        HttpGet({
            url,
            data: body,
            load: true
        }).then((result) => {
            setDetail(result)

            if (pageType != 'admin') {
                HttpPut({
                    url: '/api/bulletin/manage/read/increment',
                    data: {
                        bulletinId: bulletinId,
                        userId: userInfo.userId
                    }
                })
            }
            let attachments = result.attachmentList || result.attachments
            if (useGetIsMapArray(attachments)) {
                let imgArr = [] as any, fileArr = [] as any
                attachments.map(item => {
                    let fileType = Utils.getFileType(item.name)
                    item.url = useGetOutsideUrl(item.url, '/upload/', getBaseUrl())
                    if (fileType == 'img') {
                        imgArr.push(item)
                    } else {
                        fileArr.push(item)
                    }
                })

                // console.log(fileArr,imgArr)
                let richImgs = useGetImgInRichText(result.content)

                setRichTextImg(richImgs)
                setFileList(fileArr)
                setImgList(imgArr)
            }
        })
    }

    const getCommonData = async (params) => {
        HttpGet({ //用户信息
            url: params.baseUrl + '/api/common/user',
            data: {
                token: params.lg_tk || token,
            }
        }).then((userInfo) => {
            dispatch(setUserInfo(userInfo))
            HttpGet({ //学校信息
                url: params.baseUrl + '/api/common/system/info',
                data: {
                    eduId: userInfo.eduId,
                    token: params.lg_tk
                }
            }).then((sysInfo) => {
                dispatch(setSysInfo(sysInfo))
            })
        })
    }

    const footerOption = useMemo(() => {
        let status = Current.router?.params.status
        if (type === 'admin' && !preView) {
            if (seat == 0) {
                if (status == 1) {
                    return <View className='footer_option'>
                        <LgButton width={324} height={88} className="btn del" onClick={recall} type='D' color='close'>撤回</LgButton>
                        <LgButton width={324} height={88} className="btn" onClick={top} type='B'>置顶</LgButton>
                    </View>
                } else {
                    return <View className='footer_option'>
                        <LgButton width={648} height={88} className="btn del" onClick={del} type='D' color='close'>删除</LgButton>
                        {/* <LgButton width={324} height={88} className="btn" onClick={top} type='B'>置顶</LgButton> */}
                    </View>
                }
            } else {
                if (status == 1) {
                    return <View className='footer_option'>
                        <LgButton width={324} height={88} className="btn del" onClick={recall} type='D' color='close'>撤回</LgButton>
                        <LgButton width={324} height={88} className="btn" onClick={top} type='B'>取消置顶</LgButton>
                    </View>
                } else {
                    return <View className='footer_option'>
                        <LgButton width={628} height={88} className="btn del" onClick={del} type='D' color='close'>删除</LgButton>
                        {/* <LgButton width={324} height={88} className="btn" onClick={top} type='B'>取消置顶</LgButton> */}
                    </View>
                }

            }
        } else {
            return <></>
        }
    }, [type, detail, seat])

    const initWxSdk = async () => {
        const params = getWxSDKParams(['previewImage', 'getLocation'])
        wx.config(params);
        wx.ready(function () {
            // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
            console.log('ready')
        });
        wx.error(function (res) {
            // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
            console.log(res)
        });
    }

    useEffect(() => {
        let top = Current.router?.params.top
        setSeat(top)
        if (Utils.getSystemInfo() === 'weapp') {
            initWxSdk()
        }

        if (preView) {
            setDetail(previewData);
            let attachments = previewData.attachmentList || previewData.attachments
            if (useGetIsMapArray(attachments)) {
                let imgArr = [] as any, fileArr = [] as any
                attachments.map(item => {
                    let fileType = Utils.getFileType(item.name)
                    item.url = useGetOutsideUrl(item.url, '/upload/', getBaseUrl())
                    if (fileType == 'img') {
                        imgArr.push(item)
                    } else {
                        fileArr.push(item)
                    }
                })

                // console.log(fileArr,imgArr)
                let richImgs = useGetImgInRichText(previewData.content)

                setRichTextImg(richImgs)
                setFileList(fileArr)
                setImgList(imgArr)
            }
            return;
        }

        if (!token) {
            // 直接跳转当前详情页 需要初始化数据获取
            dispatch(setType(Utils.getQueryVariable('type')))
            let params = {
                lg_tk: Utils.getQueryVariable('lg_tk') || storage.get('token'),
                lg_ic: Utils.getQueryVariable('lg_ic') || storage.get('lg_ic'),
                baseUrl: getBaseUrl()
            }

            dispatch(setToken(params.lg_tk))
            dispatch(setIdentityCode(params.lg_ic))

            if (Utils.getSystemInfo() === 'weapp') {
                requestSystemUrl('220').then((baseUrl) => {
                    params = Object.assign({}, params, { baseUrl })
                    window.baseUrl = baseUrl
                    getCommonData(params).then(getData)
                })
            } else {
                getCommonData(params).then(getData)
            }
        } else {
            getData()
        }
    }, [])
    console.log(preView,'preView');
    
    if (!detail && !preView) {
        return <Loading />
    }

    return (
        <View className='announcement_detail'>
            {
                preView ? '' :
                    <Header
                        title='部门公告详情'
                        isLeft={true}
                        isBlod={false}
                    />
            }
            <View className='detail_container'>
                <View className='announce_header'>
                    <View className='title'>
                        {useTitleCut(detail?.title || '--', 30)}
                        {
                            detail?.typeName ?
                                <View className='department_tag'>
                                    {detail?.typeName || '--'}
                                </View> : ''
                        }

                    </View>
                    <View className='foot_tag'>
                        <View className='departant'>
                            <Text className='icon'></Text>
                            <Text>{detail?.departmentName}</Text>
                        </View>
                        <View className='time'>
                            <Text className='icon'></Text>
                            <Text>{useResetDate(detail?.releaseTime)}</Text>
                        </View>
                        {
                            type === 'admin' ?
                                <View className='count'>
                                    <Text className='icon'></Text>
                                    <Text>{detail?.readCount || '0'}</Text>
                                </View> : ''
                        }
                    </View>
                </View>
                <View className='announce_content'>
                    <View onClick={showImg} dangerouslySetInnerHTML={{ __html: detail?.content }}></View>
                </View>
                <View className='file_container'>
                    <View className='image_box'>
                        {/* <View className="imgBox"> */}
                        {
                            useGetIsMapArray(imgList) && imgList.map((item: any, index) => {
                                return (
                                    <View key={index} className="imgItem" onClick={() => showPreView(item)}>
                                        <Image className="imgSrc" src={item.url} mode='aspectFill' />
                                    </View>
                                )
                            })
                        }
                        {/* </View> */}
                    </View>
                    <View className='file_box'>
                        {
                            fileList.map((item: any, index) => {
                                let icon = Utils.getFileType(decodeURIComponent(item.name))
                                let fileIcon = {
                                    "img": "0a00901",
                                    "doc": "0a00101",
                                    "ppt": "0a00201",
                                    "pdf": "0a00501",
                                    "txt": "0a00401",
                                    "xls": "0a00301",
                                    "music": "0a00601",
                                    "video": "0a00701",
                                    "html": "0a01001",
                                    "zip": "0a01201",
                                    "otr": "0a01101"
                                }
                                let src = fileObj[fileIcon[icon]]
                                let size = Utils.getFileSize(item.size)
                                return (
                                    <FileItem
                                        key={item.attachmentId}
                                        item={item}
                                        index={index}
                                        size={size}
                                        src={src}
                                        handleDownload={handleDownload}
                                    />
                                )
                            })
                        }
                    </View>
                </View>
            </View>
            {footerOption}
            <PopoverDownload
                visible={visible}
                setVisible={setVisible}
                file={currentFile}
                index={currentIndex}
                download={download}
            />
        </View>
    )
}

export default App